/**
 * 页面组合键
 * @type {{}}
 */
import typeOfUtils from "../../utils/type-of-utils";
import {deepClone} from "../../utils";
import keyCodeUtils from "../../utils/keyCodes";
import {DirectiveOptions} from "vue";

const pageKeyCombination: DirectiveOptions = {
  bind(el, binding, vnode) {
    let modifiers = deepClone(binding.modifiers)
    if (typeOfUtils.isEmpty(modifiers)) {
      modifiers = { // 默认的组合键为ctrl + x
        ctrl: true,
        x: true
      }
    }
    // 产生组合键的位置
    // 拦截alt，shift，ctrl，meta
    const fixedButton = ['alt', 'shift', 'ctrl', 'meta']
    const hasFixedButton = []
    fixedButton.forEach(fixed => {
      if (modifiers[fixed]) {
        hasFixedButton.push(fixed)
        delete modifiers[fixed]
      }
    })
    let upKeyCode
    Object.keys(modifiers).forEach(key => {
      if (modifiers[key]) {
        upKeyCode = keyCodeUtils.getKeyCode(key);
      }
    })

    function keyupHandler(event) {
      // eslint-disable-next-line no-caller
      const e = event || window.event || arguments.callee.caller.arguments[0];
      const fixedKeyDowns = hasFixedButton.every(key => e[key + 'Key'])
      const keyCode = e.keyCode || e.which || e.charCode
      // 判断指令中是否绑定了函数
      if (fixedKeyDowns && keyCode === upKeyCode) {
        if (binding.expression) {
          // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
          if (typeOfUtils.isFunction(binding.value)) {
            binding.value();
          } else {
            alert('页面组合键必须绑定方法')
          }
        }
      }
      e.preventDefault();
      return false;
    }

    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vuePageKeyCombination__ = keyupHandler;
    document.addEventListener('keyup', keyupHandler);
  },
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener('keyup', el.__vuePageKeyCombination__);
    delete el.__vuePageKeyCombination__;
  },
}

export default pageKeyCombination
